﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace BackLib.Networking
{
    public class Client : ITCPUser
    {
        IPAddress ip;
        int port;

        public Thread clientThread;

        public Client(string IP, int port)
        {
            // Set IP, Port, and Initialzie TCPHandler
            ip = IPAddress.Parse(IP);
            this.port = port;
            Handler.client = new TcpClient();

            // Start the Connection Thread
            new Thread(Connect).Start();
        }

        public void Connect()
        {
            try
            {
                // Find out Host
                IPEndPoint serverEndPoint = new IPEndPoint(ip, port);

                // Connect
                Handler.client.Connect(serverEndPoint);
                ConnectionChanged(false, true);

                // Start Reading Incoming Data
                clientThread = new Thread(ReceiveData);
                clientThread.Start();
            }
            catch
            {
                ConnectionChanged(false, false);
            }
        }

        #region ITCPUser Members

        public void SendData(byte[] Buffer)
        {
            Handler.SendData(Buffer);
        }

        public void ReceiveData()
        {
            Handler.ReadBytes();
        }

        #endregion
    }
}
